import {Tokenizer, IDENTIFIER, INFIX_OP, PREFIX_OP} from "./Tokenizer";

export class Parse_jd {
    static precendence = [
        ['$calc(', 'ceil(', '$joint(', '${', '@(', '(', '{', '[', '@{'],
        [','],
        ['?'],
        [':'],
        ['??'],
        ['||'],
        ['&&'],
        ['|'],
        ['^'],
        ['&'],
        ['==', '!=', '===', '!=='],
        ['<', '>', '<=', '>='],
        ['<<', '>>', '>>>'],
        ['+', '-'],
        ['*', '/', '%'],
        ['**'],
        ['!', '~', '+/-', '+/+', 'typeof', 'void'],
        ['.', '?.']
    ];

    static optionMap = {
        '+': (a, b)=>parseFloat(a)+parseFloat(b)+"",
        '-': (a, b)=>parseFloat(a)-parseFloat(b)+"",
        "*": (a, b)=>parseFloat(a)*parseFloat(b)+"",
        "/": (a, b)=>parseFloat(a)/parseFloat(b)+"",
        "$calc(": (a)=>(a+""),
        "ceil(": (a)=>(a+""),
        "$joint":(a,b)=>(a+""+b),
        "==":(a,b)=>((a==b) || (a=== "null" && b === undefined)|| (a=== undefined && b === "null")),
        "!=":(a,b)=>(a!=b)
    }

    static precendenceHash = null;

    static createPrecendenceHash() {
        if (Parse_jd.precendenceHash !== null) {
            return;
        }
        Parse_jd.precendenceHash = {};
        Parse_jd.precendence.forEach(function(op, precendence) {
                op.forEach(function(op) {
                    Parse_jd.precendenceHash[op] = precendence;
                });
        });
        console.log('Precendeces:', Parse_jd.precendenceHash);
    }

    static getPrecedence(token, value) {
        let ret_value = 0
        if (Tokenizer.isFunctionCall(token)) {
            return 100;
        } else if (Tokenizer.isOperator(token)) {
            ret_value =Parse_jd.precendenceHash[value] + 1;
            return ret_value;
        } else if (Tokenizer.isLiteral(token) /*|| (token[0] == IDENTIFIER)*/) {
            return 100;
        }
        throw new Error('Could not get precedence of token:' + JSON.stringify(token));
    }

    static isOperator(token) {
        return ((token[0] == INFIX_OP) || (token[0] == PREFIX_OP));
    }
}